import { Inject, Controller, Get, Post, Put, Body, Query, Files, Fields } from '@midwayjs/core';
// import { Delete } from '@midwayjs/decorator'
import { Context } from '@midwayjs/koa';
import { PetService } from '../../service/user/pet.service';
import { Pet } from '../../entity/user/pets';
import * as fs from 'fs';
import * as path from 'path';


@Controller('/api/user')
export class APIController {
  @Inject()
  ctx: Context;

  @Inject()
  petService: PetService;


  @Get('/petinfo', { description: '获取宠物信息' })
  async getpetinfo(@Query('ownerid') ownerid: string) {
    // console.log("ownerid", ownerid);
    const result = await this.petService.getpetinfo(ownerid)
    console.log("result ",result );
    if(result.length!=0){
      for(var i = 0 ;i< result.length; i++){
        const fileName = result[i].petpic.imageurl;
        const petpic = fs.readFileSync(path.join(__dirname, '../../../public/upload', fileName));
        result[i]["src"] = petpic        
      } 
    }
    
    return { success: true, message: '获取宠物信息成功', data: { result } }
  }

  @Post('/petinfo', { description: '添加宠物信息' })
  async addpet(@Body() pet: Pet) {
    console.log(pet);
    const result = await this.petService.addpet(pet)
    return { success: true, message: '添加宠物信息成功', data: { result } }
  }

  @Put('/petinfo', { description: '更新宠物信息' })
  async updatepet(@Body() pet: Pet) {
    console.log(pet);
    const result = await this.petService.updatepet(pet)
    return { success: true, message: '更新宠物信息成功', data: { result } }
  }

  @Post('/deletepet', { description: '删除宠物信息' })
  async deletepet(@Body('petid') petid: string) {
    console.log("petid",petid);
    const result = await this.petService.deletepet(petid)
    return { success: true, message: '删除宠物成功', data: { result } }
  }

  @Post('/petpic', { description: '添加宠物图片' })
  async addpic(@Files() files, @Fields() Fields) {
    console.log("files", files);
    const image = files
    // 指定图片存储的路径
    const filePath = path.join(__dirname, '../../../public/upload', image[0].filename);
    // 将图片数据写入到指定的文件中
    fs.writeFileSync(filePath, fs.readFileSync(image[0].data));

    const result = await this.petService.addpetpic(image[0].filename, Fields.petid)
    return { success: true, message: '添加宠物图片成功', data: { result } }
  }

  @Post('/updatepetpic', { description: '更新宠物图片' })
  async updatepic(@Files() files, @Fields() Fields) {
    console.log("files", files);
    const image = files
    // 指定图片存储的路径
    const filePath = path.join(__dirname, '../../../public/upload', image[0].filename);
    // 将图片数据写入到指定的文件中
    fs.writeFileSync(filePath, fs.readFileSync(image[0].data));

    const result = await this.petService.updatepetpic(image[0].filename, Fields.petid)
    return { success: true, message: '添加宠物图片成功', data: { result } }
  }


}